package com.mxx.common.websecurity;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

/**
 * @Auther: Mr. Zeng
 * @Date: 2020/7/21 11:41
 * @Description: 暂无描述
 */
@Configuration
@ConditionalOnBean(AuthenticationParameter.class)
public class WebSecurityStrategyConfiguration extends WebSecurityConfigurerAdapter {

    @Autowired
    private AuthenticationParameter parameter;


    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        super.configure(auth);
        auth.authenticationProvider(parameter.getAuthenticationProvider())
                .userDetailsService(parameter.getAuthenticationBodyHandler())
                .passwordEncoder(parameter.getPasswordEncoder());
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        super.configure(http);
        http.authorizeRequests()
                .antMatchers(parameter.getResourcePathArray())
                .permitAll()
                .anyRequest()
                .authenticated()
                .and()
                .formLogin()
                .loginPage(parameter.getLoginPage())
                .successHandler(parameter.getSuccessHandler())
                .failureHandler(parameter.getFailureHandler())
                .authenticationDetailsSource(parameter.getAuthenticationDetailsSource())
                .permitAll()
                .and()
                .sessionManagement()
                .sessionAuthenticationFailureHandler(parameter.getSessionFailureHandler())
                .maximumSessions(1)
                .maxSessionsPreventsLogin(true)
                .expiredSessionStrategy(parameter.getSessionInformationExpiredStrategy())
                .and()
                .and()
                .logout()
                .logoutUrl(parameter.getLogoutUrl())
                .logoutSuccessHandler(parameter.getLogoutSuccessHandler())
                .and()
                .exceptionHandling()
                .and();
        if (parameter.isCsrf()) {
            http.csrf().disable().headers();
        }
        if (parameter.isSameOrigin()) {
            http.headers().frameOptions().sameOrigin();
        }
    }


}
